package ldk.apps.adbconnections

import android.app.Activity
import android.content.*
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

// 主界面
class MainActivity : Activity() {
    private val TAG = "MainActivity"

    private var mainService: MainService? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_start.setOnClickListener {
            if (mainService == null){
                startService(Intent(this, MainService::class.java))
                bind()
            }
        }

        btn_stop.setOnClickListener {
            if (mainService != null){
                mainService!!.stopService()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        bind()
        Log.v(TAG, "debugable is: ${isDebugEnable()}")
        val usbFilter = IntentFilter("android.hardware.usb.action.USB_STATE")
        val oldIntent = registerReceiver(usbStateReceiver, usbFilter)
        checkUsbStatus(oldIntent)
    }

    private fun bind() {
        bindService(Intent(this, MainService::class.java), mainServiceConnection, 0)

    }

    private fun checkUsbStatus(intent: Intent){
        val connected = intent.getBooleanExtra("connected", false)
        val adbEnabled = intent.getBooleanExtra("adb", false)

        val toast = "connected: $connected, and adbEnabled: $adbEnabled"
        Log.v(TAG, toast)
    }

    override fun onPause() {
        super.onPause()
        unbindService(mainServiceConnection)
        unregisterReceiver(usbStateReceiver)
    }

    private fun isDebugEnable(): Boolean{
        return Settings.Global.getInt(contentResolver, Settings.Global.ADB_ENABLED) == 1
    }

    private val usbStateReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            checkUsbStatus(intent)
        }
    }

    private val mainServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            Log.v(TAG, "onServiceDisConnected: ${Thread.currentThread()}")
            mainService = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder) {
            Log.v(TAG, "onServiceConnected: ${Thread.currentThread()}")
            mainService = (service as MainService.LocalBinder).service
        }
    }
}
